package cuppics;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;

import org.junit.Test;

public class Prj31 {

	/**
	 * In England the currency is made up of pound, £, and pence, p, and there
	 * are eight coins in general circulation:
	 * 
	 * 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to
	 * make £2 in the following way:
	 * 
	 * 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2
	 * be made using any number of coins?
	 */
	@Test
	public void test() {


		Calculator cal = new Calculator();
		int[] val = new int[8];
		cal.calculate(0, 200, val);
		System.out.println(cal.getCount());
	}

	public static class Calculator {

		private static final String FILE_PATH = "C:\\Users\\1440\\Desktop\\prj31.txt";

		static {
			File f = new File(FILE_PATH);
			f.delete();
		}

		private int count = 0;
		private int[] values = { 1, 2, 5, 10, 20, 50, 100, 200 };

		public void calculate(int index, int total, int[] val) {

			int len = val.length;

			if (total < 0) {
				return;
			}

			if (total == 0) {
				if (checkSum(val, 200, values)) {
					count++;
					print_arr(val);
				}
				return;
			}

			if (index == len - 1) {

				if (total % values[len - 1] == 0) {
					val[len - 1] = total / values[len - 1];
					if (checkSum(val, 200, values)) {
						count++;
						print_arr(val);
					}
				} else {

				}
				return;
			}

			for (int i = 0; i <= total / values[index]; i++) {
				int[] copy = Arrays.copyOf(val, val.length);
				copy[index] = i;
				int totalCopy = total - i * values[index];
				calculate(index + 1, totalCopy, copy);
			}

		}

		private boolean checkSum(int[] arr, int sum, int[] _values) {
			int sum1 = 0;
			for (int i = 0; i < arr.length; i++) {
				sum1 += arr[i] * _values[i];
			}
			return sum1 == sum;
		}

		public int getCount() {
			return count;
		}

		public void print_arr(int[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + ",");
			}
			System.out.println();
			saveArr(FILE_PATH, arr);
		}

		private void saveArr(String path, int[] arr) {
			File file = new File(path);

			try {
				BufferedWriter writer = new BufferedWriter(
						new OutputStreamWriter(new FileOutputStream(file, true)));

				for (int i = 0; i < arr.length; i++) {
					writer.append(String.valueOf(arr[i]) + ",");
				}
				writer.write("\t\n");
				writer.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}
}
